'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useSession } from 'next-auth/react'
import ExperimentEditForm from '@/components/experiments/ExperimentEditForm'
import { toast } from 'react-hot-toast'

interface Experiment {
  id: string;
  title: string;
  description: string;
  createdBy: {
    id: string;
    name: string | null;
    email: string;
  };
  startTime: string;
  endTime: string;
  allowLateSubmission: boolean;
  stages: any[]; // 根据实际类型调整
  authorizedExperiments: any[]; // 根据实际类型调整
  // 其他属性...
}

export default function EditExperimentPage() {
  const params = useParams()
  const router = useRouter()
  const { data: session, status } = useSession()
  const [experiment, setExperiment] = useState<Experiment | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const experimentId = params.id as string

  useEffect(() => {
    if (status === 'loading') return

    const fetchExperiment = async () => {
      try {
        setLoading(true)
        const response = await fetch(`/api/experiments/${experimentId}`)
        
        if (!response.ok) {
          throw new Error(`获取实验详情失败 (${response.status})`)
        }
        
        const data = await response.json()
        setExperiment(data.experiment)
      } catch (err: any) {
        console.error('获取实验详情错误:', err)
        setError(err.message || '获取实验详情失败')
        toast.error('获取实验详情失败，请稍后重试')
      } finally {
        setLoading(false)
      }
    }

    fetchExperiment()
  }, [experimentId, status])

  // 检查用户是否是教师/管理员
  const isTeacherOrAdmin = session?.user?.role === 'TEACHER' || session?.user?.role === 'ADMIN'
  
  // 检查用户是否是实验创建者
  const isExperimentOwner = experiment?.createdBy?.id === session?.user?.id
  
  // 检查用户是否有权编辑
  const canEdit = isTeacherOrAdmin && (isExperimentOwner || session?.user?.role === 'ADMIN')

  if (status === 'loading' || loading) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-16">
            <div className="flex justify-center">
              <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-600"></div>
            </div>
            <p className="mt-4 text-gray-600">加载实验详情中...</p>
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-red-50 border border-red-200 rounded-md p-4">
            <div className="flex">
              <div className="flex-shrink-0">
                <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                </svg>
              </div>
              <div className="ml-3">
                <h3 className="text-sm font-medium text-red-800">获取实验详情失败</h3>
                <div className="mt-2 text-sm text-red-700">
                  <p>{error}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }

  if (!experiment) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-16">
            <h3 className="mt-2 text-lg font-medium text-gray-900">实验不存在</h3>
            <p className="mt-1 text-sm text-gray-500">请检查实验ID是否正确</p>
          </div>
        </div>
      </div>
    )
  }

  if (!canEdit) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-16">
            <h3 className="mt-2 text-lg font-medium text-gray-900">无权编辑</h3>
            <p className="mt-1 text-sm text-gray-500">您没有权限编辑此实验</p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="py-8">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="mb-8">
          <h1 className="text-2xl font-semibold text-gray-900">编辑实验</h1>
          <p className="mt-2 text-sm text-gray-700">
            修改实验内容、评测标准、相关资源和授权学生。
          </p>
        </div>
        <ExperimentEditForm experiment={experiment} />
      </div>
    </div>
  )
} 